//
//  ImageBrowser.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/9/16.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SDWebImage
import ZLPhotoBrowser
import SVProgressHUD

class ImageBrowser: UICollectionView {
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: layout)
        
        register(ImageBrowserCollCell.self, forCellWithReuseIdentifier: ImageBrowserCollCell.identifer())
        //        register(self.StringFromClass(classType: ImageBrowserCollCell.self), forCellWithReuseIdentifier: )
        
        
        dataSource = self
        
        delegate = self
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        
        register(ImageBrowserCollCell.self, forCellWithReuseIdentifier: ImageBrowserCollCell.identifer())
        //        register(self.StringFromClass(classType: ImageBrowserCollCell.self), forCellWithReuseIdentifier: )
        
        
        dataSource = self
        
        delegate = self

    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    var thumPicURLs : [URL]!
    
    var bigPicURLs : [URL]?
    
    var didSelectIndex : IndexPath?
    
    lazy var browserDelegate : BrowserAnimateDelegate = BrowserAnimateDelegate()


}


extension ImageBrowser : UICollectionViewDelegate,UICollectionViewDataSource{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        
        return thumPicURLs.count
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell : ImageBrowserCollCell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageBrowserCollCell.identifer(), for: indexPath) as! ImageBrowserCollCell
        
        cell.url = thumPicURLs[indexPath.item]
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if didSelectIndex == indexPath {
            
            
            return
            
        }
        
        
        
        didSelectIndex = indexPath
        
 
        let cell = collectionView.cellForItem(at: indexPath) as! ImageBrowserCollCell
        
        let url : URL?
        
        if bigPicURLs == nil {
            url = thumPicURLs[indexPath.item]
        } else {
            url = bigPicURLs![indexPath.item]
            
        }
      
        
        SDWebImageManager.shared().downloadImage(with: url, options: SDWebImageOptions(rawValue: 0), progress: { (curret, total) in
            
            //            QL1(Thread.current)
            
            DispatchQueue.main.async {
                
                cell.progressVeiw.progress = CGFloat(curret) / CGFloat(total)
                
            }
            
            
        }) { (_, _, _, _, _) in
            
            
            let pushUrl : [URL]?
            
            if self.bigPicURLs == nil {
                pushUrl = self.thumPicURLs
            } else {
                pushUrl = self.bigPicURLs!
                
            }

            
            
            let browserVC = PhotoBrowserController(tempUrls: pushUrl!, tempIndex: indexPath)
            
            self.browserDelegate.index = indexPath
            
            self.browserDelegate.delegate = self
            
            self.browserDelegate.dimissDelegate = browserVC
            
            browserVC.transitioningDelegate = self.browserDelegate
            
            browserVC.modalPresentationStyle = .custom
            
            UIApplication.shared.keyWindow?.rootViewController?.present(browserVC, animated: true, completion: nil)
            
        }
        
        
    }
    
    
    
}


extension ImageBrowser : BrowserPresentDeleage{
    
    
    func imageBrowserView() -> ImageBrowser {
        return self
    }

    
    func browserAnimationImage(path: IndexPath) -> UIImageView{
        
        // 1.取出被点击的cell
        let cell = cellForItem(at: path) as! ImageBrowserCollCell
        // 2.拿到被点击cell上显示的图片
        let image = cell.imageView.image
        
        // 3.创建一个新的imageView
        let iv = UIImageView(image: image)
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        
        // 4.返回imageView
        return iv
        
        
        
        
    }
    // 获取被点击cell相对于keywindow的frame
    func browserAnimationFromRect(path: IndexPath) -> CGRect{
        
        
        // 1.取出被点击的cell
        let cell = cellForItem(at: path) as! ImageBrowserCollCell
        // 2.将被点击cell的坐标系从当前collectionView转换到keywindow
        let frame = convert(cell.frame, to: UIApplication.shared.keyWindow!)
        
        return frame
        
        
    }
    // 获取被点击cell中的图片, 将来在图片浏览器中显示的尺寸
    func browserAnimationToRect(path: IndexPath) -> CGRect{
        
        // 1.取出被点击的cell
        let cell = cellForItem(at: path) as! ImageBrowserCollCell
        // 2.拿到被点击cell上显示的图片
        let image = cell.imageView.image!
        // 3.计算图片宽高比
        let scale = image.size.height / image.size.width
        let height = scale * KScreenW
        
        if height > KScreenH {
            return CGRect(x: 0, y: 0, width: KScreenW, height: height)
        }else {
            let offsetY = (KScreenH - height) * 0.5
            return CGRect(x: 0, y: offsetY, width: KScreenW, height: height)
        }
        
    }
    
    
    func imageBrowserCell() -> ImageBrowserCollCell {
        
        
        return superview?.superview?.superview as! ImageBrowserCollCell
        
    }
    
    
}






class ImageBrowserCollCell: UICollectionViewCell {
    
    lazy var progressVeiw : ProgressView = {
    
     return ProgressView()
    
    }()
    
    lazy var imageView : UIImageView = {
    
        return UIImageView()
    
    }()
    
    
    lazy var GIFLabel: UILabel = {
    
        let temp = UILabel()
        
        temp.textColor = UIColor.white
        
        temp.text = "GIF"
        
        temp.font = UIFont.systemFont(ofSize: 12)
        
        temp.textAlignment = .center
        
    return temp
    }()
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        imageView.frame = bounds
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        imageView.backgroundColor = UIColor.purple
        contentView.addSubview(imageView)

        
        GIFLabel.frame = CGRect(x: bounds.size.width - 29, y: bounds.size.height - 16, width: 32, height: 16)
        GIFLabel.layer.cornerRadius = 3
        GIFLabel.layer.masksToBounds = true
        contentView.addSubview(GIFLabel)
        
 
        progressVeiw.frame = bounds
        contentView.addSubview(progressVeiw)
       
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    var url:URL?{
        
        didSet{
            
            //            imageView.sd_setImage(with: url)
            imageView.sd_setImage(with: url, completed: nil)
            

            
            GIFLabel.isHidden = !(url?.absoluteString.lowercased().hasSuffix("gif") ?? false)
            
            
        }
        
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        imageView.frame = bounds

    }
    
    
    
    
    class func identifer() -> String{
        
        return NSStringFromClass(self)
        
    }
    
}





class ImageBrowserFlowLayout: UICollectionViewFlowLayout {
    
//    init(size:CGSize,rowMargin:CGFloat){
//    super.init()
//    
//        itemSize = size
//        minimumLineSpacing = rowMargin
//        minimumInteritemSpacing = rowMargin
//        
//        
//    }
//    
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
    
    
    func calculateSize(thumPicURLs : [URL],leftRightMargin : CGFloat) ->(CGSize,CGSize){
        
        //取出配图的个数
        let imageConut = thumPicURLs.count
        
        //列数
        var col = 3.0
        
        //行数
        var row = -1
        
        //间隙
        let margin : CGFloat = 5.0
        
        //cell宽高
        let  cellW = (KScreenW - CGFloat(col - 1) * margin - leftRightMargin) / CGFloat(col)
        
        let cellH = cellW
        
        if imageConut == 0 {
            
            return (CGSize(width: 0, height: 0),CGSize(width: 0, height: 0))
            
        } else if imageConut == 1{
            let key = thumPicURLs.first!.absoluteString
            
            
            
            guard let imageCach = SDWebImageManager.shared().imageCache else {
                return (CGSize(width: 0, height: 0),CGSize(width: 0, height: 0))
                
            }
            
            guard let image = imageCach.imageFromDiskCache(forKey: key) else {
                return (CGSize(width: 0, height: 0),CGSize(width: 0, height: 0))
            }
            
            let sizehe = CGSize(width: KScreenW * 0.5, height: KScreenW * 0.5 / image.size.width * image.size.height)
            
            //UIScreen.main.nativeScale
            return (sizehe,sizehe)
//            return (image.size,image.size)
            
        }else if imageConut == 2{
            row = 1
            col = 2
            let width = cellW * CGFloat(col) + CGFloat(col - 1) * margin
            
            return (CGSize(width: width + 0.5, height: cellH),CGSize(width: cellW, height: cellH))
            
        }else if imageConut == 4{
            row = 2
            col = 2
            let width = cellW * CGFloat(col) + CGFloat(col - 1) * margin
            let height = width
            
            return (CGSize(width: width + 0.5, height: height),CGSize(width: cellW, height: cellH))
            
        }else{
            
            
            row = (imageConut - 1) / 3 + 1
            col = 3
            let width = cellW * CGFloat(col) + CGFloat(col - 1) * margin
            let height = cellW * CGFloat(row) + CGFloat(row - 1) * margin
            
            return (CGSize(width: width, height: height),CGSize(width: cellW, height: cellH))
            
            
        }
        
        
    }


    
    
    
    override func prepare() {
        super.prepare()
        
//        itemSize = CGSize(width: 20, height: 20)
        
        minimumInteritemSpacing = 5.0

        minimumLineSpacing = 5.0

        collectionView?.showsVerticalScrollIndicator = false
        
        collectionView?.showsHorizontalScrollIndicator = false
        
    }
}



class ProgressView: UIView {
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            self.backgroundColor = UIColor.clear
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    /// 进度 取值范围0.0~1.0
    var progress: CGFloat = 0.0 {
        
        
        didSet {
            
            setNeedsDisplay()
        }
    }
    
    
    
    
    override func draw(_ rect: CGRect) {
        
        // 1.过滤垃圾数据
        if progress == 1.0 {
            return
        }
        
        // 2.绘制圆形
        let center = CGPoint(x: rect.width * 0.5, y: rect.height * 0.5)
        let radius = min(rect.width * 0.5, rect.height * 0.5)
        let start = -CGFloat(Double.pi / 2)
        let end = CGFloat(2 * Double.pi) * progress + start
        let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: start, endAngle: end, clockwise: true)
        path.addLine(to: center)
        path.close()
        
        //        UIColor(white: 0.6, alpha: 0.5).setFill()
        UIColor.red.setFill()
        
        path.fill()
        
        
    }
    
}














protocol BrowserPresentDeleage : NSObjectProtocol {
    // 获取一个和被点击cell一模一样的UIImageView
    func browserAnimationImage(path: IndexPath) -> UIImageView
    // 获取被点击cell相对于keywindow的frame
    func browserAnimationFromRect(path: IndexPath) -> CGRect
    // 获取被点击cell中的图片, 将来在图片浏览器中显示的尺寸
    func browserAnimationToRect(path: IndexPath) -> CGRect
    
//    func imageBrowserView() -> ImageBrowser
    
    
}

protocol BrowserDismissDelegate : NSObjectProtocol {
    func imageViewForDismissView() -> UIImageView
    func indexPathForDismissView() -> IndexPath
}


class BrowserAnimateDelegate: NSObject {
    
    var index : IndexPath?
    
    weak var delegate : BrowserPresentDeleage?
    
    // 消失动画的代理
    weak var dimissDelegate : BrowserDismissDelegate?
    
    weak var imageBrowserView : ImageBrowser?
    
    
}



extension BrowserAnimateDelegate :UIViewControllerTransitioningDelegate{
    
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController?{
        
        let temp = UIPresentationController(presentedViewController: presented, presenting: presenting)
        
        
        return temp
        
        
    }
    
    //以下两个方法是告诉系统弹出和消失的操作有谁来管理,一旦实现系统就不会再给默认的弹出样式
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        //        myBlock(true)
        return self
    }
    
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        //        myBlock(false)
        
        return self
    }
    
}


extension BrowserAnimateDelegate:UIViewControllerAnimatedTransitioning{
    //返回动画时长
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval{
        
        
        return 0.25
        
    }
    
    // This method can only  be a nop if the transition is interactive and not a percentDriven interactive transition.
    //    弹出消失动画代码在以下方法中处理
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning){
        
        //断言
        assert(index != nil, "必须知道当前点击cell的索引才可以执行动画!")
        assert(delegate != nil, "必须有代理对象才能执行动画!")
        
        transitionContext.containerView.backgroundColor = UIColor.black
        
        let presentingView = transitionContext.view(forKey: UITransitionContextViewKey.from)
        let presentedView = transitionContext.view(forKey: UITransitionContextViewKey.to)
        
        //如果presentedView有值说明是弹出动画
        if let tempView = presentedView {
            
            //        1.新建一个ImageView, 设置ImageView的内容和被点击cell的内容一致
            let imageView = delegate!.browserAnimationImage(path: index!)
            
            //        2.设置新建的ImageView的frame和被点击cell的frame一致
            let fromRect = delegate!.browserAnimationFromRect(path: index!)
            imageView.frame = fromRect
            
//            imageBrowserView = delegate?.imageBrowserView()
            
            let hehe = delegate as? ImageBrowser
            
            hehe?.didSelectIndex = nil
            
            
            //        3.将新建的UIImageView添加到容器视图上
            transitionContext.containerView.addSubview(imageView)
            
            
            //        5.让新建的ImageView执行动画, 将图片放大到和屏幕一样宽
            let toRect = delegate!.browserAnimationToRect(path: index!)
            
            UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                
                imageView.frame = toRect
                
            }, completion: { (_) in
                //        1.删除新建的ImageView, 添加图片浏览器到容器视图上
                imageView.removeFromSuperview()
                
                transitionContext.containerView.backgroundColor = UIColor.red
                
                
                transitionContext.containerView.addSubview(tempView)
                
                transitionContext.completeTransition(true)
            })
            
        }else{
            
            
            assert(dimissDelegate != nil, "必须有代理对象才能执行动画!")
            
            transitionContext.containerView.backgroundColor = UIColor.clear
            
            
            
            // 2.获取动画的imageView
            let imageView = dimissDelegate!.imageViewForDismissView()
            
            // 3.添加到containerView中
            presentingView?.removeFromSuperview()
            transitionContext.containerView.addSubview(imageView)
            
            // 4.获取indexPath
            let indexPath = dimissDelegate!.indexPathForDismissView()
            
            
            
            
            UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                
                imageView.frame = self.delegate!.browserAnimationFromRect(path: indexPath)
                
            }, completion: { (_) in
                
                imageView.removeFromSuperview()
                transitionContext.completeTransition(true)
            })
            
            
            
            
        }
        
        
    }
    
}








class PhotoBrowserController: UIViewController {
    var urls : [URL]
    
    var indexPath : IndexPath
    
    lazy var closeBtn : UIButton = {
        let btn = UIButton(frame: CGRect(x: 10, y: KScreenH - 40, width: 75, height: 30))
        
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.backgroundColor = UIColor(colorLiteralRed: 100.0/255.0, green: 100.0/255.0, blue: 100.0/255.0, alpha: 0.7)
        btn.setTitle("关闭", for: .normal)
        btn.addTarget(self, action: #selector(closeBtnClick), for: .touchUpInside)
        btn.layer.cornerRadius = 8
        
        return btn
    }()
    
    @objc fileprivate func closeBtnClick(){
        
        view.backgroundColor = UIColor.clear
        
        dismiss(animated: true, completion: nil)
    }
    
    
    
    
    
    lazy var saveBtn : UIButton = {
        let btn = UIButton(frame: CGRect(x: KScreenW - 85, y: KScreenH - 40, width: 75, height: 30))
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.backgroundColor = UIColor(colorLiteralRed: 100.0/255.0, green: 100.0/255.0, blue: 100.0/255.0, alpha: 0.7)
        btn.setTitle("保存图片", for: .normal)
        btn.layer.cornerRadius = 8
        btn.addTarget(self, action: #selector(saveBtnClick), for: .touchUpInside)
        
        
        return btn
    }()
    
    
    
    func saveBtnClick(){
        
        let temp = collectionView.visibleCells.first as! BrowerCell
        
        ZLPhotoManager.saveImage(toAblum: temp.imageView.image) { (_, _) in
            
            SVProgressHUD.showSuccess(withStatus: "保存成功!")

        }
        
        
        
    }
    
    
    
    lazy var collectionView : UICollectionView = {
        
        let collet = UICollectionView(frame:CGRect(x: 0, y: 0, width: KScreenW + 20, height: KScreenH), collectionViewLayout: BrowserFlowLayout())
        collet.dataSource = self
        collet.delegate = self
        
        collet.register(BrowerCell.self, forCellWithReuseIdentifier: BrowerCell.identifer())
        
        return collet
    }()
    
    
    
    init(tempUrls:[URL],tempIndex:IndexPath){
        
        urls = tempUrls
        indexPath = tempIndex
        
        super.init(nibName: nil, bundle: nil)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.orange
        
        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        
        // Do any additional setup after loading the view.
    }
    
    override func viewDidLayoutSubviews() {
        
        super.viewDidLayoutSubviews()
        
        collectionView.scrollToItem(at:indexPath, at: .left, animated: false)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    
    
}

extension PhotoBrowserController:UICollectionViewDataSource,UICollectionViewDelegate{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return urls.count
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: BrowerCell.identifer(), for: indexPath) as! BrowerCell
        
        cell.url = urls[indexPath.item]
        
        cell.delegate = self
        
        return cell
        
    }
    
    
}


// 定义协议
protocol BrowserCellDelegate : NSObjectProtocol {
    func imageViewClick()
}


class BrowerCell: UICollectionViewCell {
    var url : URL?{
        
        didSet{
            
            activity.startAnimating()
            
            resetCell()
            
            
            
            imageView.sd_setImage(with: url, placeholderImage: nil, options: []) { (image, _, _, _) in
                
                self.activity.stopAnimating()
                
                guard let tmepImage = image else {
                    return
                }
                
                
                
                let screenH = UIScreen.main.bounds.size.height
                let screenW = UIScreen.main.bounds.size.width
                
                let imageHeiht = tmepImage.size.height/tmepImage.size.width * screenW
                
                self.imageView.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: screenW, height: imageHeiht)
                )
                
                if imageHeiht < screenH {
                    let offset = (screenH - imageHeiht) * 0.5
                    
                    self.scrollView.contentInset = UIEdgeInsetsMake(offset, 0, offset, 0)
                    
                    
                }else{
                    
                    self.scrollView.contentSize = self.imageView.frame.size
                    
                }
                
            }
            
            
        }
        
        
    }
    
    
    private func resetCell(){
        
        scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
        scrollView.contentSize = CGSize.zero
        scrollView.contentOffset = CGPoint.zero
        
        imageView.transform = CGAffineTransform.identity
    }
    
    
    weak var delegate : BrowserCellDelegate?
    
    
    
    
    lazy var scrollView : UIScrollView = {
        let tempView = UIScrollView(frame: UIScreen.main.bounds)
        tempView.delegate = self
        tempView.maximumZoomScale = 2.0
        tempView.minimumZoomScale = 0.5
        tempView.showsVerticalScrollIndicator = false
        tempView.showsHorizontalScrollIndicator = false
        
        return tempView
        
    }()
    
    lazy var imageView : UIImageView = {
        let tempView = UIImageView()
        tempView.contentMode = .scaleAspectFill
        tempView.isUserInteractionEnabled = true
        
        // 4.给imageView添加手势
        let tapGest = UITapGestureRecognizer(target: self, action: #selector(imageViewClick))
        tempView.addGestureRecognizer(tapGest)
        return tempView
        
        
    }()
    
    func imageViewClick() {
        
        scrollView.backgroundColor = UIColor.clear
        contentView.backgroundColor = UIColor.clear
        imageView.backgroundColor = UIColor.clear
        backgroundColor = UIColor.clear
        
        
        
        delegate?.imageViewClick()
        
    }
    
    
    lazy var activity : UIActivityIndicatorView = {
        
        let temp = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
        
        temp.center = CGPoint(x: KScreenW * 0.5, y: KScreenH * 0.5)
        
        
        return temp
    }()
    
    
    class func identifer() -> String{
        
        
        return NSStringFromClass(self)
        
    }
    
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(scrollView)
        
        scrollView.addSubview(imageView)
        
        contentView.addSubview(activity)
        
        //        activity.center = scrollView.center
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


extension BrowerCell:UIScrollViewDelegate{
    
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
        
        
        
    }
    
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        
        var offsetY = (KScreenH - imageView.frame.height) * 0.5
        
        var offsetX = (KScreenW - imageView.frame.width) * 0.5
        
        offsetX = offsetX < 0 ? 0 : offsetX
        offsetY = offsetY < 0 ? 0 : offsetY
        
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: offsetY, right: offsetX)
        
        
        
    }
    
    
    
}


class BrowserFlowLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        
        itemSize = CGSize(width: KScreenW + 20, height: KScreenH)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal
        
        
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        //        collectionView?.bounces = false
        collectionView?.isPagingEnabled = true
        
    }
}



extension PhotoBrowserController:BrowserDismissDelegate,BrowserCellDelegate{
    
    func imageViewForDismissView() -> UIImageView{
        // 1.创建UIImageView对象
        let imageView = UIImageView()
        
        // 2.设置imageView上显示的图片
        let cell = collectionView.visibleCells.first as! BrowerCell
        imageView.image = cell.imageView.image
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        
        // 3.设置imageView的frame
        // 3.1.计算高度
        let height = KScreenW / imageView.image!.size.width * imageView.image!.size.height
        
        // 3.2.计算y值
        var y : CGFloat = 0
        if height < KScreenH {
            y = (KScreenH - height) * 0.5
        } else {
            y = 0
        }
        
        // 3.3.设置frame
        imageView.frame = CGRect(x: 0, y: y, width: KScreenW, height: height)
        
        return imageView
        
    }
    
    
    
    func indexPathForDismissView() -> IndexPath{
        
        
        return collectionView.indexPathsForVisibleItems.first!
        
        
    }
    
    
    
    func imageViewClick(){
        
        closeBtnClick()
        
        
    }
    
    
    
    
    
    
}

